# -*- encoding: utf-8 -*-
'''
@File    :   app.py
@Time    :   2022/03/26 10:42:02
@Author  :   yueke 
@Version :   1.0
@Contact :   huangyanting@zsc.edu.cn
@Desc    :   None
'''



from data import SourceData
from data_creek import CreekData

import logging

import eventlet
import json
from flask import Flask, render_template
from flask_mqtt import Mqtt
from flask_socketio import SocketIO
from flask_bootstrap import Bootstrap

eventlet.monkey_patch()

app = Flask(__name__)
app.config['SECRET'] = 'my secret key'
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['MQTT_BROKER_URL'] = '120.78.157.190'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_CLIENT_ID'] = 'flask_mqtt'
app.config['MQTT_CLEAN_SESSION'] = True
app.config['MQTT_USERNAME'] = 'test'
app.config['MQTT_PASSWORD'] = 'test'
app.config['MQTT_KEEPALIVE'] = 20
app.config['MQTT_TLS_ENABLED'] = False
app.config['MQTT_LAST_WILL_TOPIC'] = 'hechongtopic'
app.config['MQTT_LAST_WILL_MESSAGE'] = 'bye'
app.config['MQTT_LAST_WILL_QOS'] = 2

mqtt = Mqtt(app)
mqtt.subscribe("hechongtopic", 1)
mqtt.subscribe("yoloxtopic", 1)
socketio = SocketIO(app)
bootstrap = Bootstrap(app)

'''
定义了2个网址，用同一套模板渲染
'''
@app.route('/default')
def index():
    # 新建一个实例
    creekdata = SourceData()
    # 传入一个实例，和实例的标题
    return render_template('index.html', form=creekdata, title=creekdata.title)

@app.route('/')
def corp():
    creekdata = CreekData()
    return render_template('index_creek.html', form=creekdata, title=creekdata.title)

@app.route('/creekmqtt')
def creekmqtt():
    creekdata = CreekData()
    return render_template('index_mqtt.html', form=creekdata, title=creekdata.title)

@socketio.on('publish')
def handle_publish(json_str):
    data = json.loads(json_str)
    mqtt.publish(data['topic'], data['message'], data['qos'])


@socketio.on('subscribe')
def handle_subscribe(json_str):
    data = json.loads(json_str)
    mqtt.subscribe(data['topic'], data['qos'])

@socketio.on('unsubscribe_all')
def handle_unsubscribe_all():
    mqtt.unsubscribe_all()


@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    data = dict(
        topic=message.topic,
        payload=message.payload.decode(),
        qos=message.qos,
    )
    socketio.emit('mqtt_message', data=data)


@mqtt.on_log()
def handle_logging(client, userdata, level, buf):
    # print(level, buf)
    pass

if __name__ == "__main__":
    # app.run(host='0.0.0.0')    
    socketio.run(app, host='0.0.0.0', port=5001, use_reloader=False, debug = True)
